package com.xfp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xfp.context.BaseContext;
import com.xfp.mapper.CategoryMapper;
import com.xfp.mapper.GoodsMapper;
import com.xfp.method.pageTotal;
import com.xfp.pojo.dto.GoodsDto;
import com.xfp.pojo.dto.GoodsQueryDto;
import com.xfp.pojo.entity.Category;
import com.xfp.pojo.entity.Goods;
import com.xfp.pojo.vo.GoodsQueryVo;
import com.xfp.pojo.vo.PageVo;
import com.xfp.service.GoodsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class GoodsSerivceImp implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增商品
     *
     * @param goodsDto
     * @return
     */
    @Override
    public Boolean insert(GoodsDto goodsDto) {
        Long time = System.currentTimeMillis();
        goodsDto.setSkuId(time+"");
        //查询商品是否存在
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsDto, goods);
        int n = goodsMapper.insert(goods);
        boolean b = false;
        if (n == 1) {
            b = true;
        }
        return b;
    }

    /**
     * 分页查询商品实现
     */
    @Override
    public GoodsQueryVo page(GoodsQueryDto goodsQueryDto) {
        //启用分页插件
        PageHelper.startPage(goodsQueryDto.getPageIndex(), goodsQueryDto.getPageSize());
        //查询商品基础数据
        List<Goods> goodsList = goodsMapper.page(goodsQueryDto);
        //补全商品信息
        goodsList.forEach(goods -> {
            //查询商品分类信息
            Category category = categoryMapper.findById(goods.getClassId());
            goods.setClassName(category.getClassName());
            goods.setSkuClass(category);
        });
        Page page = (Page) goodsList;
        //总页码数
        Long l = pageTotal.total(page.getTotal(), goodsQueryDto.getPageSize());
        GoodsQueryVo vo  = new GoodsQueryVo();
        vo.setPageIndex(goodsQueryDto.getPageIndex());
        vo.setPageSize(goodsQueryDto.getPageSize());
        vo.setTotalPage(l);
        vo.setTotalCount(page.getTotal());
        vo.setCurrentPageRecords(page.getResult());
        return vo;
    }

    /**
     * 修改商品信息
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean update(String id,GoodsDto dto) {
        dto.setSkuId(id);
        int n = goodsMapper.update(dto);
        boolean b = false;
        if (n != 0)
            b = true;
        return b;
    }
}
